package com.advertisementsystem.Servie.Impl;

import com.advertisementsystem.Dto.AdvertisementDTO;
import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Mapper.AdScheduleMapper;
import com.advertisementsystem.Mapper.AdvertisementMapper;
import com.advertisementsystem.Servie.AdvertisementService;
import com.advertisementsystem.Servie.UserService;
import com.advertisementsystem.entity.Schedule;
import com.advertisementsystem.entity.Advertisement;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;


@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class AdvertisementServiceImpl implements AdvertisementService {

    @Autowired
    private AdvertisementMapper advertisementMapper;

    @Override
    public void createAdvertisement(AdvertisementDTO dto) {

        // 获取当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        // 创建广告
        Advertisement ad = new Advertisement();
        BeanUtils.copyProperties(dto, ad);
        ad.setAdvertiserId(loginUser.getUser().getId());
        ad.setStatus(0); // 待审核状态
        ad.setCreatedTime(LocalDateTime.now());
        ad.setUpdatedTime(LocalDateTime.now());

        advertisementMapper.insert(ad);
    }

    @Override
    public void updateAdvertisement(Long id, AdvertisementDTO dto) {
        // 检查广告是否存在
        Advertisement ad = advertisementMapper.selectById(id);
        if (ad == null) {
            throw new RuntimeException("广告不存在");
        }

        // 检查权限
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        if (!ad.getAdvertiserId().equals(loginUser.getUser().getId())&&!loginUser.getPermissions().contains("ROLE_ADMIN")) {
            throw new RuntimeException("无权修改此广告");
        }

        // 更新广告
        BeanUtils.copyProperties(dto, ad);
        ad.setUpdatedTime(LocalDateTime.now());
        advertisementMapper.updateById(ad);
    }

    @Override
    public void deleteAdvertisement(Long id) {
        // 检查广告是否存在
        Advertisement ad = advertisementMapper.selectById(id);
        if (ad == null) {
            throw new RuntimeException("广告不存在");
        }

        // 检查权限
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        if (!ad.getAdvertiserId().equals(loginUser.getUser().getId())&&!loginUser.getPermissions().contains("ROLE_ADMIN")) {
            throw new RuntimeException("无权删除此广告");
        }

        // 删除广告
        advertisementMapper.deleteById(id);
    }
    @Override
    public Page<Advertisement> getAdvertisementList(Integer pageNum, Integer pageSize, String keyword,
                                                    String status, String budget, String sort, Integer type) {
        Page<Advertisement> page = new Page<>(pageNum, pageSize);

        // 获取当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        // 构建查询条件
        LambdaQueryWrapper<Advertisement> wrapper = new LambdaQueryWrapper<>();

        log.info("用户角色权限: {}", loginUser.getPermissions());

        // 根据不同角色设置不同的查询条件
        if (loginUser.getPermissions().contains("ROLE_ADVERTISER")) {
            // 广告主只能看到自己的广告
            wrapper.eq(Advertisement::getAdvertiserId, loginUser.getUser().getId());
        } else if (loginUser.getPermissions().contains("ROLE_DEVICE_OWNER")) {
            // 设备主默认只能看到已审核通过的广告
            wrapper.eq(Advertisement::getStatus, 1); // 1表示已审核通过
        }
        // 管理员可以看到所有广告，不需要额外条件

        // 添加关键词搜索条件
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(Advertisement::getTitle, keyword);
        }

        if (type != null)
        {
            wrapper.eq(Advertisement::getType, type);
        }
        // 添加状态筛选条件 (如果设备主指定了状态筛选，仍然只能查看已审核的广告)
        if (StringUtils.isNotBlank(status) && !loginUser.getPermissions().contains("ROLE_DEVICE_OWNER")) {
            wrapper.eq(Advertisement::getStatus, Integer.parseInt(status));
        }

        // 添加预算范围筛选条件
        if (StringUtils.isNotBlank(budget)) {
            String[] budgetRange = budget.split("-");
            if (budgetRange.length > 0) {
                BigDecimal minBudget = new BigDecimal(budgetRange[0]);
                wrapper.ge(Advertisement::getBudget, minBudget);

                if (budgetRange.length > 1 && StringUtils.isNotBlank(budgetRange[1])) {
                    BigDecimal maxBudget = new BigDecimal(budgetRange[1]);
                    wrapper.le(Advertisement::getBudget, maxBudget);
                }
            }
        }

        // 添加排序条件
        switch (sort) {
            case "budget_desc":
                wrapper.orderByDesc(Advertisement::getBudget);
                break;
            case "budget_asc":
                wrapper.orderByAsc(Advertisement::getBudget);
                break;
            case "start_desc":
                wrapper.orderByDesc(Advertisement::getStartTime);
                break;
            case "time_desc":
            default:
                wrapper.orderByDesc(Advertisement::getCreatedTime);
                break;
        }

        // 执行查询
        Page<Advertisement> resultPage = advertisementMapper.selectPage(page, wrapper);

        // 查询结果记录
        log.info("广告查询结果：分页 {}/{}, 总数: {}, 条件: 关键词={}, 状态={}, 预算={}, 排序={}",
                resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal(),
                keyword, status, budget, sort);

        return resultPage;
    }
    // @Override
    // public Page<Advertisement> getAdvertisementList(Integer pageNum, Integer pageSize) {
    //     Page<Advertisement> page = new Page<>(pageNum, pageSize);
    //
    //     // 获取当前用户
    //     LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
    //             .getAuthentication()
    //             .getPrincipal();
    //
    //     // 构建查询条件
    //     LambdaQueryWrapper<Advertisement> wrapper = new LambdaQueryWrapper<>();
    //
    //     log.info("{}",loginUser.getPermissions());
    //     // 根据不同角色设置不同的查询条件
    //     if (loginUser.getPermissions().contains("ROLE_ADVERTISER")) {
    //         // 广告主只能看到自己的广告
    //         wrapper.eq(Advertisement::getAdvertiserId, loginUser.getUser().getId());
    //     } else if (loginUser.getPermissions().contains("ROLE_DEVICE_OWNER")) {
    //         // 设备主只能看到已审核通过的广告
    //         wrapper.eq(Advertisement::getStatus, 1); // 1表示已审核通过
    //     }
    //     // 管理员可以看到所有广告，不需要额外条件
    //
    //     // 按创建时间倒序排序
    //      wrapper.orderByDesc(Advertisement::getCreatedTime);
    //     Page<Advertisement> p = advertisementMapper.selectPage(page, wrapper);
    //     log.info("查询结果：{}", p);
    //     return p;
    // }
    @Override
    public Advertisement getAdvertisementDetail(Long id) {
        return advertisementMapper.selectById(id);
    }

    @Override
    @PreAuthorize("hasRole('ADMIN')")
    public void approveAdvertisement(Long id) {
        Advertisement ad = advertisementMapper.selectById(id);
        if (ad == null) {
            throw new RuntimeException("广告不存在");
        }

        ad.setStatus(1); // 已审核状态
        ad.setUpdatedTime(LocalDateTime.now());
        advertisementMapper.updateById(ad);
    }

    @Override
    @PreAuthorize("hasRole('ADMIN')")
    public void rejectAdvertisement(Long id) {
        Advertisement ad = advertisementMapper.selectById(id);
        if (ad == null) {
            throw new RuntimeException("广告不存在");
        }

        ad.setStatus(4); // 已拒绝状态
        ad.setUpdatedTime(LocalDateTime.now());
        advertisementMapper.updateById(ad);
    }

    @Override
    public Page<Advertisement> getAdvertisementsByUserId(Long userId, Integer pageNum, Integer pageSize, String title, Integer status, String startDate, String endDate,Integer type) {

        // 创建分页对象
        Page<Advertisement> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        QueryWrapper<Advertisement> queryWrapper = new QueryWrapper<>();

        // 添加用户ID条件
        queryWrapper.eq("advertiser_id", userId);

        // 添加标题模糊查询
        if (StringUtils.isNotBlank(title)) {
            queryWrapper.like("title", title);
        }

        // 添加状态条件
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        if (type != null)
        {
            queryWrapper.eq("type", type);
        }
        // 添加时间范围条件
        if (StringUtils.isNotBlank(startDate)) {
            queryWrapper.ge("start_time", startDate + " 00:00:00");
        }
        if (StringUtils.isNotBlank(endDate)) {
            queryWrapper.le("end_time", endDate + " 23:59:59");
        }

        // 添加排序条件（按创建时间降序）
        queryWrapper.orderByDesc("created_time");

        // 执行查询
        return advertisementMapper.selectPage(page, queryWrapper);
    }
}